package com.wangy.net.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

import com.wangy.io.StreamUtil;

public class HttpUtil {

	private static HttpURLConnection conn = null;
	private static String sessionId = null;
	private static RequestMethod method = RequestMethod.GET;

	public static HttpURLConnection init(String url, RequestMethod method) {
		try {
			conn = (HttpURLConnection) new URL(url).openConnection();
			if (method == null)
				conn.setRequestMethod(RequestMethod.GET.getValue());
			else
				conn.setRequestMethod(method.getValue());
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setInstanceFollowRedirects(false);
			if (sessionId != null) {
				conn.setRequestProperty("Cookie", sessionId);
			}
			conn.setRequestProperty("User-Agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
			conn.setRequestProperty("Connection", "keep-alive");
			conn.connect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static OutputStream getOutputStream(String url) {
		init(url, method);
		try {
			return conn.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static InputStream getInputStream(String url) {
		init(url, method);
		try {
			return conn.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static RequestResult request(String url, RequestMethod method,
			Map<String, String> params) throws IOException {
		init(url, method);
		OutputStreamWriter outWriter = null;
		StringBuffer buffer = new StringBuffer();
		if (params != null) {
			for (Entry<String, String> entry : params.entrySet()) {
				buffer.append(entry.getKey() + "=" + entry.getValue() + "&");
			}
			try {
				outWriter = new OutputStreamWriter(conn.getOutputStream(),
						"utf-8");
				outWriter.write(buffer.toString());
				outWriter.flush();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (outWriter != null)
						outWriter.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return RequestResult.create(conn);
	}

	public static String getContent(String url, RequestMethod method,
			Map<String, String> params) throws IOException {
		request(url, method, params);
		return new String(StreamUtil.readToByte(conn.getInputStream()), "UTF-8");
	}

	public static String getSession(String url, RequestMethod method,
			Map<String, String> params) throws IOException {
		request(url, method, params);
		sessionId = conn.getHeaderField("Set-Cookie");
		System.out.println("sessionId:" + sessionId);
		return sessionId;
	}

	public static boolean download(String url) {
		try {
			conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Range", "bytes=" + 0 + "-");
			conn.setConnectTimeout(5000);
			if (sessionId != null) {
				conn.setRequestProperty("Cookie", sessionId);
			}
			conn.connect();
			int contentLength = conn.getContentLength();
			String disposition = conn.getHeaderField("Content-Disposition");
			new DownloadThread(conn.getInputStream(), contentLength,
					getdownloadFileName(disposition, url)).start();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	private static String getdownloadFileName(String disposition, String url) {
		if (disposition != null && !disposition.equals("")) {
			return disposition.split("=")[1].replace("\"", "");
		} else if (url.contains("/")) {
			return url.substring(url.lastIndexOf("/") + 1);
		}
		return "unkown";
	}

	public static String getSessionId() {
		return sessionId;
	}

	public static void setSessionId(String sessionId) {
		HttpUtil.sessionId = sessionId;
	}

}
